const std = @import("std");
const struct__win_st = @cImport({
	@cInclude("ncurses.h");
}).struct__win_st;

const CellChar = @import("constants.zig").CellChar;
const CellCharType = @import("constants.zig").CellCharType;
const CellColor = @import("constants.zig").CellColor;
const Grid = @import("grid.zig").Grid;
const GridCell = @import("grid.zig").Cell;


pub const PipesGrid = struct {
	width: u8,
	height: u8,
	_grid: Grid(CellCharType) = undefined,


	pub fn init(self: *PipesGrid, window: *struct__win_st) !void {
		self._grid = Grid(CellCharType){
			.width = self.width,
			.height = self.height,
			.empty_char = @intFromEnum(CellChar.EMPTY),
			.empty_color_pair_id = @intFromEnum(CellColor.NORMAL),
			.window = window,
		};
		try self._grid.init();
	}


	pub fn deinit(self: *PipesGrid) void {
		self._grid.deinit();
	}


	pub fn display(self: *PipesGrid) !void {
		const win_size_x: c_int = self._grid.get_window_size_x();
		const win_size_y: c_int = self._grid.get_window_size_y();
		const left_pad: c_int = @divFloor(win_size_x, 2) - self.width;
		const top_pad: c_int = @divFloor(win_size_y - self.height, 2);

		for (self._grid.get_grid(), 0..) |row, row_idx| {
			const r_idx: c_int = @intCast(row_idx);
			self._grid.set_cursor_pos(r_idx + top_pad, left_pad);

			for (row) |cell| {
				self._grid.print_cell(&cell);
				self._grid.print_cell(&PipesGrid.get_gap_cell(cell));
			}
			self._grid.print_str("\n\r");
		}
		self._grid.show();
	}


	pub fn clear(self: *PipesGrid) void {
		self._grid.clear();
	}


	pub fn set_cell(self: *PipesGrid, x: u8, y: u8, char: CellCharType,
			color_pair_id: u8) void {
		self._grid.set_cell(x, y, char, color_pair_id);
	}


	fn get_gap_cell(cell: GridCell(CellCharType))
			GridCell(CellCharType) {
		const pipe_horiz_char = @intFromEnum(CellChar.PIPE_HORIZ);
		const pipe_corner_1_char = @intFromEnum(CellChar.PIPE_CORNER_1);
		const pipe_corner_4_char = @intFromEnum(CellChar.PIPE_CORNER_4);
		const pipe_end_1_char = @intFromEnum(CellChar.PIPE_END_1);
		const normal_color_id = @intFromEnum(CellColor.NORMAL);

		if (cell.char == pipe_horiz_char) {
			return cell;
		} else if (cell.char == pipe_corner_1_char) {
			return GridCell(CellCharType){
				.char = @intFromEnum(CellChar.PIPE_HORIZ),
				.color_pair_id = cell.color_pair_id,
			};
		} else if (cell.char == pipe_corner_4_char) {
			return GridCell(CellCharType){
				.char = @intFromEnum(CellChar.PIPE_HORIZ),
				.color_pair_id = cell.color_pair_id,
			};
		} else if (cell.char == pipe_end_1_char) {
			return GridCell(CellCharType){
				.char = @intFromEnum(CellChar.PIPE_HORIZ),
				.color_pair_id = cell.color_pair_id,
			};
		} else {
			return GridCell(CellCharType){
				.char = ' ',
				.color_pair_id = normal_color_id,
			};
		}
	}
};
